<template>
  <div class="flow h-full w-full">
    <Toolbar />
    <Sidebar />
    <VueFlow
      :nodes="nodes"
      :edges="edges"
      :node-types="nodeTypes"
      :edge-types="edgeTypes"
      :apply-default="false"
      :connection-mode="ConnectionMode.Strict"
    >
    </VueFlow>
  </div>
</template>
<script setup lang="ts">
import { ConnectionMode, VueFlow, useVueFlow } from "@vue-flow/core";
import type { Node, Edge } from "@vue-flow/core";
import { markRaw, onMounted, ref } from "vue";
import { v4 as uuidv4 } from "uuid";
// custom
import CustomNode from "./node/index.vue";
import CustomEdge from "./edge/index.vue";

const {
  emits,
  onConnect,
  snapToGrid,
  onNodesChange,
  applyNodeChanges,
  onEdgesChange,
  applyEdgeChanges,
} = useVueFlow();
emits.updateNodeInternals();
snapToGrid.value = true;
const nodes = ref<Node[]>([]);
const edges = ref<Edge[]>([]);
// node type
const nodeTypes = {
  custom: markRaw(CustomNode),
};
const edgeTypes = {
  custom: markRaw(CustomEdge),
};

onMounted(() => {
  addNode();
  addNode();
  addNode();
  addEdge();
});
onConnect(({ source, target, sourceHandle, targetHandle }) => {
  edges.value.push({
    id: uuidv4(),
    // type: "custom",
    source,
    target,
    sourceHandle,
    targetHandle,
  });
});

onNodesChange((changes) => {
  applyNodeChanges(changes);
});
onEdgesChange((changes) => {
  applyEdgeChanges(changes);
});
function addNode() {
  let id = uuidv4();
  nodes.value.push({
    id,
    type: "custom",
    connectable: true,
    selectable: true,
    data: { label: id.slice(0, 5) },
    position: { x: Math.random() * 500, y: Math.random() * 500 },
  });
}

function addEdge() {
  let id = uuidv4();
  edges.value.push({
    id,
    type: "custom",
    label: "111",
    data: { label: "hello" },
    source: nodes.value[0].id,
    target: nodes.value[1].id,
  });
}
</script>
<style lang="less">
:root {
  --vf-node-bg: red;
  --vf-node-text: #fff;
}
</style>
